package org.example.ims.Entity.User;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.*;
import lombok.*;
import org.example.ims.Entity.Base.Salesman;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CustomUser implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; // 推荐使用 Long 作为主键

    @Column(unique = true, nullable = false)
    private String username;

    @JsonIgnore
    private String password;

    private boolean enabled ;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
    @Column(name = "role_name")
    private List<String> roles; // 存储格式：["ROLE_ADMIN", "ROLE_USER"]


    @OneToOne
    @JoinColumn(name = "salesman_id")
    @JsonIgnore
    private Salesman salesman;  // 关联业务用户


    // 反序列化时从 JSON 中读取 "password" 字段
    @JsonProperty("password")
    public void setPassword(String password) {
        this.password = password;
    }

    // 序列化时忽略 getPassword() 方法
    @JsonIgnore
    @Override
    public String getPassword() {
        return password;
    }

    // ===== UserDetails Methods =====

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true; // 可根据业务需求修改
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}